﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using WH.NurseSys.BLL;
using WH.NurseSys.Model;

namespace WH.NurseSys.Report
{
    public partial class PatientListForm : Form
    {
        PatientBLL patientBLL = new PatientBLL();
        int pageIndex = 1, pageSize = 10000, pageCount = 1,rowCount=0;
        PatientSearchArg searchArg;

        public PatientListForm()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }

        //构建查询条件对象
        PatientSearchArg buildSearchArg()
        {
            PatientSearchArg searchArg = new PatientSearchArg();
            if (!string.IsNullOrEmpty(textBoxName.Text))
                searchArg.Name = textBoxName.Text;
            if (comboBoxInHosp.SelectedIndex == 0)
                searchArg.InHospStatus = new bool[] { true };
            else if (comboBoxInHosp.SelectedIndex == 1)
                searchArg.InHospStatus = new bool[] { false };
            else if (comboBoxInHosp.SelectedIndex == 2)
                searchArg.InHospStatus = new bool[] { true, false };
            searchArg.DeptId = (Guid)comboBoxDept.SelectedValue;
            return searchArg;
        }

        //开始查询病人列表
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            searchArg = this.buildSearchArg();
            search();
        }

        //开始查询病人列表
        private void search()
        {
            buttonSearch.Enabled = false;
            toolStripProgressBar.Style = ProgressBarStyle.Marquee;
            toolStripStatusLabelMsg.Text = "正在查询数据";            
            backgroundWorkerPatient.RunWorkerAsync(searchArg);
        }

        //异步查询病人列表
        private void backgroundWorkerPatient_DoWork(object sender, DoWorkEventArgs e)
        {
            rowCount = patientBLL.GetQueryCount((PatientSearchArg)e.Argument);           
            List<Patient> patientList = patientBLL.GePagedQueryList(pageIndex,pageSize,(PatientSearchArg)e.Argument);
            e.Result = patientList;
        }

        //异步查询病人列表完成
        private void backgroundWorkerPatient_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar.Style = ProgressBarStyle.Continuous;
            toolStripStatusLabelMsg.Text = "查询已完成";
            setPage();
            List<Patient> patientList = e.Result as List<Patient>;
            buttonSearch.Enabled = true;
            listViewPatient.Items.Clear();
            listViewPatient.BeginUpdate();
            bool backgroundSwitch = false;
            foreach (Patient patient in patientList)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = string.Empty;              
                lvi.SubItems.Add(patient.Name);
                lvi.SubItems.Add(patient.Gender ? "男" : "女");
                lvi.SubItems.Add(patient.Age.ToString() + (patient.AgeUnit == "D" ? "天" : "岁"));
                lvi.SubItems.Add(patient.BedNo);
                lvi.SubItems.Add(patient.InpatientNo);
                lvi.SubItems.Add(patient.InDate.ToString("yyyy-MM-dd HH:mm"));
                lvi.SubItems.Add(patient.DeptName);
                lvi.SubItems.Add(patient.Doctor);
                if (patient.InHosp)
                    lvi.SubItems.Add("◆");
                else
                    lvi.SubItems.Add(string.Empty);
                lvi.Tag = patient;
                if (backgroundSwitch)
                    lvi.BackColor = Color.FromArgb(0xf0, 0xf0, 0xf0);
                backgroundSwitch = !backgroundSwitch;
                listViewPatient.Items.Add(lvi);
                
            }
            listViewPatient.EndUpdate();
        }

        //设置分页信息
        void setPage()
        {
            if (rowCount % pageSize == 0)
            {
                pageCount = rowCount / pageSize;
                if (pageCount <= 0)
                    pageCount = 1;
            }
            else
            {
                pageCount = rowCount / pageSize + 1;
            }
            labelPatientCount.Text = rowCount.ToString();
            labelPageCount.Text = pageCount.ToString();
            textBoxPageIndex.Text = pageIndex.ToString();
        }

        //窗口加载
        private void MainForm_Load(object sender, EventArgs e)
        {
            List<Dept> deptList = new List<Dept>();
            Dept dept = new Dept {Id=new Guid(ConfigurationManager.AppSettings["deptId"]),Name=ConfigurationManager.AppSettings["deptName"] };
            deptList.Add(dept);
            if (ConfigurationManager.AppSettings["rank"] == "3")
            {
                dept = new Dept { Id = Guid.Empty, Name = "全部" };
                deptList.Add(dept);
            }         
            comboBoxDept.DataSource = deptList;
            comboBoxDept.ValueMember = "Id";
            comboBoxDept.DisplayMember = "Name";
            comboBoxInHosp.SelectedIndex = 0;
            //listview
            ColumnHeader colHeaderStatus = new ColumnHeader();
            colHeaderStatus.Text = string.Empty;
            colHeaderStatus.Width = 30;
            listViewPatient.Columns.Add(colHeaderStatus);
            ColumnHeader colHeaderName = new ColumnHeader();
            colHeaderName.Text = "姓名";
            colHeaderName.Width = 90;
            listViewPatient.Columns.Add(colHeaderName);
            ColumnHeader colHeaderGender = new ColumnHeader();
            colHeaderGender.Text = "性别";
            colHeaderGender.Width = 60;
            listViewPatient.Columns.Add(colHeaderGender);
            ColumnHeader colHeaderAge = new ColumnHeader();
            colHeaderAge.Text = "年龄";
            colHeaderAge.Width = 70;
            listViewPatient.Columns.Add(colHeaderAge);
            ColumnHeader colHeaderBedNo = new ColumnHeader();
            colHeaderBedNo.Text = "床号";
            colHeaderBedNo.Width = 120;
            listViewPatient.Columns.Add(colHeaderBedNo);
            ColumnHeader colHeaderInpatientNo = new ColumnHeader();
            colHeaderInpatientNo.Text = "住院号";
            colHeaderInpatientNo.Width = 120;
            listViewPatient.Columns.Add(colHeaderInpatientNo);
            ColumnHeader colHeaderInDate = new ColumnHeader();
            colHeaderInDate.Text = "登记时间";
            colHeaderInDate.Width = 230;
            listViewPatient.Columns.Add(colHeaderInDate);
            ColumnHeader colHeaderDeptName = new ColumnHeader();
            colHeaderDeptName.Text = "科室";
            colHeaderDeptName.Width = 150;
            listViewPatient.Columns.Add(colHeaderDeptName);
            ColumnHeader colHeaderDoctor = new ColumnHeader();
            colHeaderDoctor.Text = "医生";
            colHeaderDoctor.Width = 120;
            listViewPatient.Columns.Add(colHeaderDoctor);
            ColumnHeader colHeaderInHosp = new ColumnHeader();
            colHeaderInHosp.Text = "在院";
            colHeaderInHosp.Width = 60;
            listViewPatient.Columns.Add(colHeaderInHosp);
        }

        //查看病人检查数据
        private void listViewPatient_ItemActivate(object sender, EventArgs e)
        {
            Patient patient = listViewPatient.SelectedItems[0].Tag as Patient;
            RecordForm recordForm = new RecordForm(patient);
            recordForm.ShowDialog();
        }

        //清空登录信息，退出
        private void toolStripButtonLogout_Click(object sender, EventArgs e)
        {
            ConfigHelper.SetAppSetting("nickname", string.Empty);
            ConfigHelper.SetAppSetting("userId", string.Empty);
            ConfigHelper.SetAppSetting("deptId", string.Empty);
            ConfigHelper.SetAppSetting("deptName", string.Empty);
            ConfigHelper.SetAppSetting("rank", string.Empty);
            this.Close();
        }

        //登记建立新的病人档案
        private void toolStripButtonNew_Click(object sender, EventArgs e)
        {
            EditPatientForm editPatientForm = new EditPatientForm();
            editPatientForm.ShowDialog();
        }

        //编辑选中的病人信息
        private void toolStripButtonEdit_Click(object sender, EventArgs e)
        {
            editPatient();
        }

        //编辑选中的病人
        private void editPatient()
        {
            if (listViewPatient.SelectedItems.Count <= 0)
            {
                return;
            }
            Patient patient = listViewPatient.SelectedItems[0].Tag as Patient;
            EditPatientForm editPatientForm = new EditPatientForm(patient);
            editPatientForm.ShowDialog();
        }

        //删除一个选中的病人
        private void deletePatient()
        {
            if (listViewPatient.SelectedItems.Count <= 0)
                return;
            if (MessageBox.Show("是否确认要删除这个病人，该操作不可恢复!", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                Patient patient = listViewPatient.SelectedItems[0].Tag as Patient;
                if (!backgroundWorkerDelete.IsBusy)
                {
                    backgroundWorkerDelete.RunWorkerAsync(patient.Id);
                    toolStripProgressBar.Style = ProgressBarStyle.Marquee;
                    toolStripStatusLabelMsg.Text = "正在删除";
                }
            }
        }

        //为一个病人办出院
        private void leaveHospPatient()
        {
            if (listViewPatient.SelectedItems.Count <= 0)
                return;
            Patient patient = listViewPatient.SelectedItems[0].Tag as Patient;
            if (patient.InHosp == false)
            {
                MessageBox.Show("病人并不在院，无需出院");
                return;
            }
            if (MessageBox.Show("是否要为这个病人办理出院!", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {

                if (!backgroundWorkerLeaveHosp.IsBusy)
                {
                    backgroundWorkerLeaveHosp.RunWorkerAsync(patient);
                    toolStripProgressBar.Style = ProgressBarStyle.Marquee;
                    toolStripStatusLabelMsg.Text = "正在办理出院";
                }
            }
        }

        //为选中的病人切换科室
        private void changeDeptPatient()
        {
            if (listViewPatient.SelectedItems.Count <= 0)
                return;
            Patient patient = listViewPatient.SelectedItems[0].Tag as Patient;
            TranslateDeptForm translateDeptForm = new TranslateDeptForm(patient);
            translateDeptForm.ShowDialog();
        }

        //删除一个病人
        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            deletePatient();
        }

        //异步删除病人
        private void backgroundWorkerDelete_DoWork(object sender, DoWorkEventArgs e)
        {
            Guid patientId = (Guid)e.Argument;
            e.Result=patientBLL.Delete(patientId);
        }

        //删除完成
        private void backgroundWorkerDelete_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar.Style = ProgressBarStyle.Continuous;           
            if ((bool)e.Result)
            {
                toolStripStatusLabelMsg.Text = "删除成功";
                search();
            }
            else
                toolStripStatusLabelMsg.Text = "删除失败";
        }

        //异步切换出院
        private void backgroundWorkerLeaveHosp_DoWork(object sender, DoWorkEventArgs e)
        {
            Patient patient = e.Argument as Patient;
            patient.InHosp = false;
            e.Result=patientBLL.Update(patient);
        }

        //异步办理出院完成
        private void backgroundWorkerLeaveHosp_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar.Style = ProgressBarStyle.Continuous;            
            if ((bool)e.Result)
            {
                toolStripStatusLabelMsg.Text = "办理出院成功";
                search();
            }
            else
                toolStripStatusLabelMsg.Text = "出院失败";
        }

        //出院
        private void ToolStripMenuItemLeaveHosp_Click(object sender, EventArgs e)
        {
            leaveHospPatient();
        }

        //办理转科
        private void ToolStripMenuItemChangeDept_Click(object sender, EventArgs e)
        {
            changeDeptPatient();
        }

        //编辑病人信息
        private void ToolStripMenuItemEdit_Click(object sender, EventArgs e)
        {
            editPatient();
        }

        //为病人办理转科
        private void ToolStripMenuItemTranslateDept_Click(object sender, EventArgs e)
        {
            changeDeptPatient();
        }

        //删除一个选中的病人
        private void ToolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            deletePatient();
        }

        //为选中的病人，修改为出院
        private void ToolStripMenuItemLeaveHospC_Click(object sender, EventArgs e)
        {
            leaveHospPatient();
        }

        //加载第一页
        private void buttonFirstPage_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex = 1;
                search();
            }
        }

        //加载上一页
        private void buttonPreviousPage_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                search();
            }
        }

        //加载下一页
        private void buttonNextPage_Click(object sender, EventArgs e)
        {
            if (pageIndex < pageCount)
            {
                pageIndex++;
                search();
            }
        }

        //加载末页
        private void buttonLastPage_Click(object sender, EventArgs e)
        {
            if (pageIndex < pageCount)
            {
                pageIndex = pageCount;
                search();
            }
        }


    }
}
